package com.wqz.tacos.controller;

import com.wqz.tacos.models.Ingredient;
import com.wqz.tacos.models.Taco;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

// 处理http请求或者将http请求传递给视图，又或者将数据直接写入响应体Restful
// Slf4j用于生成logger
// Controller将会标注这个类为控制器类
// RequestMapping用于类级别的时候可以显示地规定该类只会处理路径以"/design"开头的请求
@Slf4j
@Controller
@RequestMapping("/design")
public class DesignTackController {
    //@GetMapping
    @ModelAttribute()
    public void addIngredientToModel(Model model) {
        // 直接构造数据
        List<Ingredient> ingredients = Arrays.asList(
                new Ingredient("FLTO", "Flour Tortilla", Ingredient.Type.WRAP),
                new Ingredient("COTO", "Corn Tortilla", Ingredient.Type.WRAP),
                new Ingredient("GRBF", "Ground Beef", Ingredient.Type.PROTEIN),
                new Ingredient("CARN","Carnitas", Ingredient.Type.PROTEIN),
                new Ingredient("TMTO", "Carnitas", Ingredient.Type.VEGGIES),
                new Ingredient("LETC", "Lettuce", Ingredient.Type.VEGGIES),
                new Ingredient("CHED", "Cheddar", Ingredient.Type.CHEESES),
                new Ingredient("JACK", "Monterrey Jack", Ingredient.Type.CHEESES),
                new Ingredient("SLSA", "Salsa", Ingredient.Type.SAUCES),
                new Ingredient("SRCR", "Sour Cream", Ingredient.Type.SAUCES)
        );

        // 根据配料类型过滤列表
        Ingredient.Type[] types = Ingredient.Type.values();
        for (Ingredient.Type type : types) {
            model.addAttribute(type.toString().toLowerCase(), filterByType(ingredients, type));
        }
    }

    // showDesignForm[]
    // 这里按照书上的会出错，mapping有问题
    @GetMapping
    public String showDesignForm(Model model) {
        model.addAttribute("design", new Taco());
        return "design";
    }

    @PostMapping
    public String processDesign(@Valid @ModelAttribute("design") Taco design, Errors errors) {
        if (errors.hasErrors()) {
            log.info("ingredient error occurred and it is " + errors.toString());
            return "design";
        }
        // Save the taco design...
        log.info("Processing design: " + design);

        return "redirect:/orders/current";
    }

    private List<Ingredient> filterByType(List<Ingredient> ingredients, Ingredient.Type type) {
        return ingredients
                .stream()
                .filter(x -> x.getType().equals(type))
                .collect(Collectors.toList());
    }
}
